import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:flutter_hsh/fluttergromore/ads/ad_feed_view.dart';
import 'package:get/get.dart';

import 'phone_cooldown_binding.dart';
import 'phone_cooldown_logic.dart';

/// 手机降温页面
/// 效果：
/// 1）动画页：CPU芯片上有横向高亮扫过的效果，下面是温度计液柱（蓝色）随进度缓慢上升/下降；周围有雪花轻微飘落；顶部AppBar标题“手机降温”。
/// 2）完成页：圆环勾选图标、提示“温度将在60秒后降低3.0℃”，2秒后自动返回。
class PhoneCoolDownPage extends StatelessWidget {
  const PhoneCoolDownPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<PhoneCoolDownLogic>(
      init: PhoneCoolDownLogic(),
      builder: (_) {
        return Scaffold(
          // 顶部导航栏
          appBar: AppBar(
            title: const Text('手机降温'),
            backgroundColor: Colors.blue,
            foregroundColor: Colors.white,
            elevation: 0,
          ),
          body: Obx(() {
            // 根据是否展示完成页切换内容
            return _.showSuccess.value
                ? _buildSuccessView(_)
                : _buildCoolingView(context, _);
          }),
        );
      },
    );
  }

  /// 降温动画页
  Widget _buildCoolingView(BuildContext context, PhoneCoolDownLogic logic) {
    final size = MediaQuery.of(context).size;
    return Stack(
      children: [
        // 渐变背景，接近截图的浅蓝色渐变
        Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Color(0xFF6EB7FF), // 上部偏蓝
                Color(0xFF9BD3FF), // 中部更浅
                Color(0xFFBEE6FF), // 下部淡蓝
              ],
            ),
          ),
        ),

        // 雪花飘落（简单位移动画）
        Positioned.fill(
          child: Obx(() {
            final p = logic.progress.value;
            return CustomPaint(
              painter: _SnowPainter(p),
            );
          }),
        ),

        // 中心内容：CPU芯片 + 温度计 + 进度与提示
        Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // CPU芯片（带横向高亮扫过）
              _CpuChip(progress: logic.progress),
              const SizedBox(height: 16),
              // 温度计（蓝色液柱根据进度变化）
              _Thermometer(progress: logic.progress),
              const SizedBox(height: 24),
              // 进度条与文案
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 32.0),
                child: Column(
                  children: [
                    LinearProgressIndicator(
                      value: logic.progress.value,
                      minHeight: 6,
                      backgroundColor: Colors.white.withOpacity(0.4),
                      valueColor:
                          const AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                    const SizedBox(height: 12),
                    Text(
                      logic.statusText.value,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 完成页（与截图风格接近）
  Widget _buildSuccessView(PhoneCoolDownLogic logic) {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Color(0xFF6EB7FF), Color(0xFF9BD3FF), Color(0xFFBEE6FF)],
        ),
      ),
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 圆环+勾选图标（简单静态实现，易读）
            Container(
              width: 80,
              height: 80,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white.withOpacity(0.8), width: 2),
              ),
              child: const Icon(Icons.check, color: Colors.white, size: 40),
            ),
            const SizedBox(height: 16),
            // 文案：温度将在60秒后降低X℃
            RichText(
              text: TextSpan(
                children: [
                  const TextSpan(
                    text: '温度将在60秒后降低',
                    style: TextStyle(color: Colors.white, fontSize: 16),
                  ),
                  TextSpan(
                    text: '${logic.targetDropDegrees.value.toStringAsFixed(1)}℃',
                    style: const TextStyle(
                      color: Color(0xFFE6FF4F), // 黄绿突出色
                      fontSize: 16,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 10,),
            const MyAdFeedView()
          ],
        ),
      ),
    );
  }
}

/// CPU芯片控件：带横向高亮扫过的视觉（模拟截图中的亮条）
class _CpuChip extends StatelessWidget {
  final RxDouble progress;
  const _CpuChip({required this.progress});

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final p = progress.value;
      return Stack(
        alignment: Alignment.center,
        children: [
          // 芯片主体
          Container(
            width: 120,
            height: 120,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.85),
              borderRadius: BorderRadius.circular(16),
              boxShadow: [
                BoxShadow(
                  color: Colors.white.withOpacity(0.6),
                  blurRadius: 30,
                  spreadRadius: 2,
                ),
              ],
              border: Border.all(color: Colors.white, width: 2),
            ),
            alignment: Alignment.center,
            child: Text(
              'CPU',
              style: TextStyle(
                color: Colors.blue.shade600,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          // 横向高亮条（根据进度在芯片中上下移动）
          Positioned(
            top: 20 + (80 * (1 - p)),
            left: 0,
            right: 0,
            child: Container(
              height: 8,
              margin: const EdgeInsets.symmetric(horizontal: 8),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.9),
                borderRadius: BorderRadius.circular(8),
              ),
            ),
          ),
        ],
      );
    });
  }
}

/// 温度计控件：白色外壳+蓝色液柱，液柱高度与progress关联
class _Thermometer extends StatelessWidget {
  final RxDouble progress;
  const _Thermometer({required this.progress});

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final p = progress.value; // 0~1
      const double width = 60;
      const double height = 160;
      const double bulbSize = 44;
      final double liquidHeight = (height - bulbSize) * (0.2 + 0.7 * p);

      return SizedBox(
        width: width,
        height: height + bulbSize,
        child: Stack(
          alignment: Alignment.topCenter,
          children: [
            // 白色外壳
            Positioned(
              top: 0,
              child: Container(
                width: 24,
                height: height,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
            ),
            // 蓝色液柱
            Positioned(
              top: height - liquidHeight,
              child: Container(
                width: 16,
                height: liquidHeight,
                decoration: BoxDecoration(
                  color: const Color(0xFF3DA6FF),
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
            ),
            // 底部圆形温度计球泡
            Positioned(
              top: height - 4,
              child: Container(
                width: bulbSize,
                height: bulbSize,
                decoration: BoxDecoration(
                  color: const Color(0xFF3DA6FF),
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: const Color(0xFF3DA6FF).withOpacity(0.5),
                      blurRadius: 16,
                      spreadRadius: 2,
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    });
  }
}

/// 简易雪花绘制（使用CustomPainter减少Widget数量）
class _SnowPainter extends CustomPainter {
  final double progress;
  _SnowPainter(this.progress);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..color = Colors.white.withOpacity(0.35);
    // 多个雪花点位，随进度轻微位移（向下）
    for (int i = 0; i < 8; i++) {
      final dx = (size.width / 9) * (i + 1);
      final baseY = (size.height / 8) * (i + 1);
      final dy = baseY + 20 * math.sin(progress * math.pi * (i + 1));
      canvas.drawCircle(Offset(dx, dy), 3.0 + (i % 3), paint);
    }
  }

  @override
  bool shouldRepaint(covariant _SnowPainter oldDelegate) {
    // 进度变化时重绘
    return oldDelegate.progress != progress;
  }
}